package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import module.DetailModule;

import bean.ResultFlag;

import com.google.gson.Gson;

public class DetailController extends HttpServlet {

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		Gson gson=new Gson();
		ResultFlag flag=new ResultFlag();
		DetailModule detail=new DetailModule();
		String action=request.getParameter("action");
		//get this shop all message
		if(action.equals("getThisShop")){
			String itemId=request.getParameter("itemId");
			int id=Integer.parseInt(itemId);
			try {
				ArrayList list=detail.getItemMsg(id);
				String thisShopMSg=gson.toJson(list);
				out.print(thisShopMSg);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//run addcart action
		else if(action.equals("addCart")){
			int itemId=Integer.parseInt(request.getParameter("itemId"));
			int shopNum=Integer.parseInt(request.getParameter("shopNum"));
			int userId=Integer.parseInt(request.getParameter("userId"));
			float price=Float.parseFloat(request.getParameter("price"));
			String picture=request.getParameter("picture");
			String shopname=request.getParameter("shopname");
			try {
				int addCartFlag=detail.addCart(itemId, shopNum, shopname, picture,userId,price);
				flag.setFlag(addCartFlag);
				String flagJson=gson.toJson(flag);
				out.print(flagJson);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		out.flush();
		out.close();
	}

}
